package business
{
	import com.adobe.cairngorm.business.ServiceLocator;
	
	import model.BabyChartModelLocator;
	
	import mx.rpc.AsyncToken;
	import mx.rpc.IResponder;
	import mx.rpc.http.HTTPService;
	
	import util.DateConverter;
	
	import vo.Baby;
	import vo.BabyData;
	
	public class BabyDelegate
	{
		private var responder : IResponder;
		private var service :HTTPService;
		
		public function BabyDelegate(responder:IResponder)
		{
			this.responder = responder;
		}

		public function loadBabyData(firstname:String, lastname:String, dob:Date, password:String):void {
			if (firstname == "Test" && lastname == "User") {
				this.service = ServiceLocator.getInstance().getHTTPService("loadSampleBabyService");
			} else {
				this.service = ServiceLocator.getInstance().getHTTPService("loadBabyService");
			}
			
			var call:AsyncToken = service.send({firstname:firstname, lastname:lastname, dob:DateConverter.formatDate(dob), password:password});
			call.addResponder(responder);
		}
		
		public function saveBabyData(newps:String):void {
			this.service = ServiceLocator.getInstance().getHTTPService("saveBabyService");
			var baby:Baby = BabyChartModelLocator.getInstance().baby;
			
			var saveBabyRequest:XML = <baby>
									      <id>{isNaN(baby.id) ? 0 : baby.id}</id>
									      <firstname>{(baby.firstname == null) ? '' : baby.firstname}</firstname>
									      <lastname>{baby.lastname == null ? '' : baby.lastname}</lastname>
									      <dob>{DateConverter.formatDate(baby.dob)}</dob>
									      <password>{baby.password == null ? '' : baby.password}</password>
									      <newpassword>{newps}</newpassword>
									      <gender>{baby.gender}</gender>
									      <metric>{baby.metric}</metric>
									  </baby>;
			var dataXml:XML = <data></data>;
			for each (var datapoint:BabyData in baby.data) {
				if (datapoint.date != null) {
					var datapointXml:XML = <datapoint></datapoint>;
					datapointXml.appendChild(<id>{isNaN(datapoint.id) ? 0 : datapoint.id}</id>);
					datapointXml.appendChild(<date>{DateConverter.formatDate(datapoint.date)}</date>);
					datapointXml.appendChild(<weight>{isNaN(datapoint.weight) ? 0 : datapoint.weight}</weight>);
					datapointXml.appendChild(<length>{isNaN(datapoint.height) ? 0 : datapoint.height}</length>);
					datapointXml.appendChild(<headCircumference>{isNaN(datapoint.headCircumference) ? 0 : datapoint.headCircumference}</headCircumference>);
					dataXml.appendChild(datapointXml);
				}
			}
			saveBabyRequest.appendChild(dataXml);
			
			var call:AsyncToken = service.send({xml:saveBabyRequest});
			call.addResponder(responder);
		}
	}
}